﻿// ===============================================================================
// XCI.WinForm.Platform 西安交通信息WinForm开发框架 2019 版权所有
// ===============================================================================

using System.ComponentModel;
using XCI.Sys.Service;
using XCI.Windows.Controls;
using XCI.Sys.Model;
using XCI.Windows;
using System.Collections.Generic;
using System;
using DevExpress.XtraEditors.ViewInfo;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors.Drawing;
using System.Drawing;
using DevExpress.XtraEditors.Registrator;

namespace XCI.Sys.Controls
{
    /// <summary>
    /// 数据字典多选控件
    /// </summary>
    [System.ComponentModel.DesignerCategory("Code")]
    public class DicCheckedListBox : CheckedListBoxControlx
    {
        static DicCheckedListBox()
        {

        }

        public DicCheckedListBox()
        {
        }

        private AsyncWorker asyncWorker;

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public override string ValueMember => "Value";
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public override string DisplayMember => "Name";

        /// <summary>
        /// 字典编码
        /// </summary>
        [Category("XCI"), DefaultValue(null), Description("字典编码")]
        public string DicCode { get; set; }

        /// <summary>
        /// 异步数据加载完成事件
        /// </summary>
        [Category("XCI"), Description("异步数据加载完成事件")]
        public event EventHandler<EventArgs> DataLoadComplet;

        /// <summary>
        /// 是否异步加载
        /// </summary>
        [Category("XCI")]
        [Description("是否异步加载")]
        [DefaultValue(true)]
        public bool AsyncLoad { get; set; } = true;

        protected override void OnLoaded()
        {
            base.OnLoaded();
            if (DesignMode) return;
            if (string.IsNullOrEmpty(DicCode)) return;
            this.CheckOnClick = true;
            this.MultiColumn = true;
            this.SelectionMode = System.Windows.Forms.SelectionMode.None;
            this.ShowFocusRect = false;

            List<SysDic> list = null;
            if (AsyncLoad)
            {
                if (asyncWorker == null) asyncWorker = new AsyncWorker();
                asyncWorker.RunCallback(e => { list = DicService.Instance.SelectListByCode(DicCode); })
                .CompletCallback(e => BindData(list))
                .RunAsync();
            }
            else
            {
                list = DicService.Instance.SelectListByCode(DicCode);
                BindData(list);
            }
        }

        private void BindData(List<SysDic> list)
        {
            DataSource = list;
            DataLoadComplet?.Invoke(this, EventArgs.Empty);
        }
    }
}